package com.excel.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.corpgovernment.common.apollo.BasicManageApollo;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.dataloader.BasicOssClientLoader;
import com.excel.entity.db.PubImpExcelJdLog;
import com.excel.service.OssService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;

/**
 *
 *  @author hc
 * 
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OssServiceImpl implements OssService {

	@Autowired
	private BasicOssClientLoader basicOssClientLoader;
	@Autowired
	private BasicManageApollo basicServerApollo;


	@Override
	@SneakyThrows
	public XSSFWorkbook getExcelByOss(PubImpExcelJdLog pubImpExcelJdLog) {
		XSSFWorkbook workBook = null;
		String ossUrl = basicOssClientLoader.privateGeneratePresignedUrl(pubImpExcelJdLog.getSouceFilePath());
		URL urlFile = null;
		HttpURLConnection httpUrl = null;
		try {
			if (ossUrl == null) {
				throw new CorpBusinessException(OrganizationResponseCodeEnum.FILE_IS_NULL);
			}
			urlFile = new URL(ossUrl);
			if (ObjectUtil.isNotEmpty(basicServerApollo.getProxyUrl()) && ObjectUtil.isNotEmpty(basicServerApollo.getProxyPort())) {
				Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(basicServerApollo.getProxyUrl(), basicServerApollo.getProxyPort()));
				httpUrl = (HttpURLConnection) urlFile.openConnection(proxy);
			} else {
				httpUrl = (HttpURLConnection) urlFile.openConnection();
			}
			httpUrl.connect();
			workBook = new XSSFWorkbook(httpUrl.getInputStream());
		}catch (IOException e) {
			log.error("下载模板异常", e);
		} finally {
			if(httpUrl!=null){
				httpUrl.disconnect();
			}
		}
		return workBook;
	}
}
